package com.probox.common.entity.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.entity.service.system.ISysMenuService;
import com.probox.common.entity.service.system.ISysPermissionService;
import com.probox.common.entity.service.system.ISysRoleService;
import com.probox.common.redis.service.RedisService;
import com.probox.systemApi.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class SysPermissionServiceImpl implements ISysPermissionService {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取角色数据权限
     *
     * @param userId 用户Id
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(Long userId) {
        String key = CachePrefix.WEB_USER_ROLE + userId;
        Set<String> roles = redisService.getCacheSet(key);
        if (ObjectUtil.isEmpty(roles)) {
            roles = new HashSet<String>();
            // 管理员拥有所有权限
            if (SysUser.isAdmin(userId)) {
                roles.add("admin");
            } else {
                roles.addAll(roleService.selectRolePermissionByUserId(userId));
            }

            if (ObjectUtil.isNotEmpty(roles)) {
                redisService.setCacheSet(key, roles);
                redisService.expire(key, 1, TimeUnit.DAYS);
            }
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param userId 用户Id
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(Long userId) {
        String key = CachePrefix.WEB_USER_PERMISSION + userId;
        Set<String> perms = redisService.getCacheSet(key);
        if (ObjectUtil.isEmpty(perms)) {
            perms = new HashSet<String>();
            // 管理员拥有所有权限
            if (SysUser.isAdmin(userId)) {
                perms.add("*:*:*");
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(userId));
            }
            if (ObjectUtil.isNotEmpty(perms)) {
                redisService.setCacheSet(key, perms);
                redisService.expire(key, 1, TimeUnit.DAYS);
            }
        }
        return perms;
    }
}
